package com.ruoyi.security.service.backtest.gridtrading.service.impl;

import com.ruoyi.security.convert.SecurityGridTradingBacktestHistoryConvert;
import com.ruoyi.security.domain.SecurityGridTradingBacktestDetailsHistory;
import com.ruoyi.security.domain.SecurityGridTradingBacktestHistory;
import com.ruoyi.security.domain.SecurityGridTradingBacktestDayDetailsHistory;
import com.ruoyi.security.dto.backtest.SecurityGridTradingBacktestResultDto;
import com.ruoyi.security.mapper.SecurityGridTradingBacktestHistoryDayDetailsMapper;
import com.ruoyi.security.mapper.SecurityGridTradingBacktestHistoryDetailsMapper;
import com.ruoyi.security.mapper.SecurityGridTradingBacktestHistoryMapper;
import com.ruoyi.security.service.backtest.gridtrading.service.ISecurityGridTradingBacktestHistoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yeoman
 * @date 2025/11/13 15:01
 * @description 网格交易回测历史记录
 */
@Service
public class SecurityGridTradingBacktestHistoryServiceImpl implements ISecurityGridTradingBacktestHistoryService {

    @Resource
    private SecurityGridTradingBacktestHistoryMapper historyMapper;

    @Resource
    private SecurityGridTradingBacktestHistoryDayDetailsMapper dayDetailsMapper;

    @Resource
    private SecurityGridTradingBacktestHistoryDetailsMapper detailsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(SecurityGridTradingBacktestResultDto backtestResultDto) {

        SecurityGridTradingBacktestHistory history = SecurityGridTradingBacktestHistoryConvert.INSTANCE.toSecurityGridTradingBacktestHistory(backtestResultDto);
        historyMapper.insert(history);

        List<SecurityGridTradingBacktestResultDto.DayDetail> dayDetailList = backtestResultDto.getDayDetailList();
        for (SecurityGridTradingBacktestResultDto.DayDetail dayDetail : dayDetailList) {
            SecurityGridTradingBacktestDayDetailsHistory dayDetails = SecurityGridTradingBacktestHistoryConvert.INSTANCE.toSecurityGridTradingBacktestHistoryDayDetails(dayDetail);
            dayDetails.setBacktestHistoryId(history.getId());
            dayDetailsMapper.insert(dayDetails);

             List<SecurityGridTradingBacktestResultDto.DayDetail.Detail> detailList = dayDetail.getDetails();
            for (SecurityGridTradingBacktestResultDto.DayDetail.Detail detail : detailList) {
                SecurityGridTradingBacktestDetailsHistory details = SecurityGridTradingBacktestHistoryConvert.INSTANCE.toSecurityGridTradingBacktestHistoryDetails(detail);
                details.setBacktestHistoryDayId(dayDetails.getId());
                detailsMapper.insert(details);
            }
        }
    }

}
